import { createI18n } from 'vue-i18n'
import zhCN from './zh-CN.json'
import zhHK from './zh-HK.json'
import enUS from './en-US.json'

// 支持的语言列表
export const SUPPORTED_LOCALES = [
  { code: 'zh-CN', name: '简体中文', flag: '🇨🇳' },
  { code: 'zh-HK', name: '繁體中文（香港）', flag: '🇭🇰' },
  { code: 'en-US', name: 'English', flag: '🇺🇸' }
] as const

export type SupportedLocale = typeof SUPPORTED_LOCALES[number]['code']

// 获取浏览器默认语言
function getDefaultLocale(): SupportedLocale {
  const stored = localStorage.getItem('locale') as SupportedLocale
  if (stored && SUPPORTED_LOCALES.some(locale => locale.code === stored)) {
    return stored
  }

  // 检查浏览器语言
  const browserLang = navigator.language.toLowerCase()
  if (browserLang.includes('zh-hk') || browserLang.includes('zh-tw')) {
    return 'zh-HK'
  }
  if (browserLang.includes('en')) {
    return 'en-US'
  }

  return 'zh-CN' // 默认简体中文
}

// 创建 i18n 实例
export const i18n = createI18n({
  legacy: false, // 使用 Composition API
  locale: getDefaultLocale(),
  fallbackLocale: 'zh-CN',
  messages: {
    'zh-CN': zhCN,
    'zh-HK': zhHK,
    'en-US': enUS
  },
  globalInjection: true // 全局注入 $t
})

// 切换语言的工具函数
export function setLocale(locale: SupportedLocale) {
  i18n.global.locale.value = locale
  localStorage.setItem('locale', locale)
  document.documentElement.lang = locale
}

// 获取当前语言
export function getCurrentLocale(): SupportedLocale {
  return i18n.global.locale.value as SupportedLocale
}

// 获取语言显示名称
export function getLocaleName(locale: SupportedLocale): string {
  const found = SUPPORTED_LOCALES.find(l => l.code === locale)
  return found?.name || locale
}
